import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index'

Vue.use(VueRouter)

const routes = [
  { path: '/login', name: 'login', component: () => import('@/views/Login/index.vue') },
  {
    path: '/',
    name: 'layout',
    redirect: '/welcome',
    component: () => import('@/views/Layout/index.vue'),
    children: [
      { path: '/welcome', name: 'welcome', component: () => import('@/views/welCome/index.vue') },
      { path: '/users', name: 'users', component: () => import('@/views/user/userList.vue') },
      { path: '/goods', name: 'goods', component: () => import('@/views/goods/component/goodsList.vue') },
      { path: '/goods/add', name: 'addgoods', component: () => import('@/views/goods/modules/addGoods.vue') },
      { path: '/categories', name: 'categories', component: () => import('@/views/goods/component/categories.vue') },
      { path: '/params', name: 'params', component: () => import('@/views/goods/component/params.vue') },
      { path: '/roles', name: 'roles', component: () => import('@/views/roles/index.vue') },
      { path: '/rights', name: 'rights', component: () => import('@/views/roles/rights.vue') },
      { path: '/orders', name: 'orders', component: () => import('@/views/orders/index.vue') },
      { path: '/reports', name: 'reports', component: () => import('@/views/reports/index.vue') },
      { path: '/test', name: 'test', component: () => import('@/views/test/test.vue') }
    ]
  }
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

const whiteList = ['/login']
router.beforeEach((to, form, next) => {
  const token = store.state.login.token
  if (token) {
    if (whiteList.includes(to.path)) {
      next('/')
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
